package tasks;

import core.Executor;
import core.Peer;
import core.TorrentManager;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

public class Listen implements Runnable {

    private int port;
    private ExecutorService threadPool;

    public Listen(int port) {
        this.port = port;
        this.threadPool = Executor.getThreadPool();
    }

    @Override
    public void run() {
        ServerSocket ss = null;
        Socket sc = null;

        try {
            ss = new ServerSocket(port);

            while (true) {
                sc = ss.accept();
                Peer peer = new Peer(sc);
                this.threadPool.execute(new ReadHandshake(peer));
                
            }
        } catch (Exception e) {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e1) {
                }
            }
        }
    }

}
